﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using HelixToolkit.Wpf;
using ifcengineWpf.IFCEngine;

namespace ifcengineWpf
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private HybridIFCModelManager? _hybridModelManager;
        private readonly Dictionary<string, SolidColorBrush> _entityColors;
        private bool _isSearching = false;

        public MainWindow()
        {
            InitializeComponent();
            InitializeViewer();
            
            // 初始化实体颜色映射
            _entityColors = new Dictionary<string, SolidColorBrush>
            {
                ["IFCWALL"] = new SolidColorBrush(Colors.LightBlue),
                ["IFCDOOR"] = new SolidColorBrush(Colors.Brown),
                ["IFCWINDOW"] = new SolidColorBrush(Colors.LightCyan),
                ["IFCSLAB"] = new SolidColorBrush(Colors.Gray),
                ["IFCBEAM"] = new SolidColorBrush(Colors.Orange),
                ["IFCCOLUMN"] = new SolidColorBrush(Colors.Red),
                ["IFCSPACE"] = new SolidColorBrush(Colors.LightGreen),
                ["IFCSTAIR"] = new SolidColorBrush(Colors.Purple),
                ["IFCROOF"] = new SolidColorBrush(Colors.DarkRed),
                ["DEFAULT"] = new SolidColorBrush(Colors.LightGray)
            };
        }

        private void InitializeViewer()
        {
            try
            {
                _hybridModelManager = new HybridIFCModelManager();
                
                // 设置初始状态
                UpdateUI();
                statusText.Text = $"就绪 - {_hybridModelManager.CurrentMode}";
            }
            catch (Exception ex)
            {
                ShowError("初始化错误", $"应用程序初始化失败: {ex.Message}");
                btnLoadIFC.IsEnabled = false;
            }
        }

        private async void btnLoadIFC_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "IFC files (*.ifc)|*.ifc|All files (*.*)|*.*",
                Title = "选择IFC文件",
                Multiselect = false
            };

            if (openFileDialog.ShowDialog() == true)
            {
                // 验证文件格式
                if (!IFCEngineTest.ValidateIFCFile(openFileDialog.FileName))
                {
                    return;
                }
                
                await LoadIFCFileAsync(openFileDialog.FileName);
            }
        }

        private async Task LoadIFCFileAsync(string filePath)
        {
            try
            {
                LogDebug($"开始加载IFC文件: {filePath}");
                
                // 显示加载进度
                ShowLoadingPanel(true, "正在加载IFC文件...");
                statusText.Text = "加载中...";
                
                // 禁用UI控件
                SetUIEnabled(false);

                bool loadSuccess = false;
                Exception? loadException = null;
                
                await Task.Run(() =>
                {
                    try
                    {
                        Dispatcher.Invoke(() =>
                        {
                            loadingText.Text = "正在分析文件格式...";
                        });

                        loadSuccess = _hybridModelManager?.LoadModel(filePath) == true;
                    }
                    catch (Exception ex)
                    {
                        loadException = ex;
                        LogError($"加载异常: {ex.Message}");
                    }
                });

                if (loadException != null)
                {
                    HandleLoadException(loadException, filePath);
                }
                else if (loadSuccess)
                {
                    // 更新UI
                    // txtCurrentFile.Text = Path.GetFileName(filePath); // 注释掉不存在的控件
                    UpdateModelInfo();
                    UpdateEntityTree();
                    LoadGeometry();
                    UpdateUI();
                    
                    statusText.Text = $"已加载: {Path.GetFileName(filePath)}";
                    
                    // 显示加载成功信息
                    var modelInfo = _hybridModelManager?.ModelInfo;
                    if (modelInfo != null)
                    {
                        var engineMode = _hybridModelManager?.CurrentMode ?? "未知";
                        ShowInfo("加载成功", 
                            $"IFC文件加载完成\n\n" +
                            $"加载模式: {engineMode}\n" +
                            $"文件: {modelInfo.FileName}\n" +
                            $"Schema: {modelInfo.Schema}\n" +
                            $"实体数量: {modelInfo.EntityCount}\n" +
                            $"几何对象: {modelInfo.GeometryCount}\n\n" +
                            $"主要实体类型:\n" +
                            string.Join("\n", modelInfo.EntityTypeCount
                                .OrderByDescending(kv => kv.Value)
                                .Take(5)
                                .Select(kv => $"  {kv.Key}: {kv.Value}")));
                    }
                }
                else
                {
                    HandleLoadException(new Exception("未知原因导致加载失败"), filePath);
                }
            }
            catch (Exception ex)
            {
                HandleLoadException(ex, filePath);
            }
            finally
            {
                ShowLoadingPanel(false);
                SetUIEnabled(true);
            }
        }

        private void HandleLoadException(Exception ex, string filePath)
        {
            LogError($"处理加载异常: {ex.Message}");
            
            string errorTitle = "IFC文件加载失败";
            string errorMessage;
            
            if (ex is IFCLoadException ifcEx)
            {
                // 使用新的详细错误描述
                errorMessage = $"文件: {Path.GetFileName(filePath)}\n\n{ifcEx.GetDetailedErrorDescription()}";
                
                // 添加修复建议
                errorMessage += $"\n修复建议:\n{ifcEx.GetRepairSuggestions()}";
                
                // 对于特定错误类型，提供额外的操作选项
                if (ifcEx.ErrorType == IFCLoadError.EngineInitializationFailed)
                {
                    var result = MessageBox.Show(
                        errorMessage + "\n\n是否运行详细诊断？",
                        errorTitle,
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Error);
                    
                    if (result == MessageBoxResult.Yes)
                    {
                        btnTestEngine_Click(this, new RoutedEventArgs());
                    }
                }
                else if (ifcEx.ErrorType == IFCLoadError.InvalidFileFormat && ifcEx.Win32ErrorCode == 0)
                {
                    // 特殊处理：API成功但返回空句柄的情况
                    errorMessage += "\n\n特殊提示：";
                    errorMessage += "\n• 这通常表示文件格式不被当前引擎版本支持";
                    errorMessage += "\n• 文件可能使用了不兼容的IFC扩展";
                    errorMessage += "\n• 考虑使用不同版本的IFC引擎";
                    
                    var result = MessageBox.Show(
                        errorMessage + "\n\n是否尝试创建简化的测试文件？",
                        errorTitle,
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Error);
                    
                    if (result == MessageBoxResult.Yes)
                    {
                        CreateSimplifiedTestFile(filePath);
                    }
                    else
                    {
                        ShowError(errorTitle, errorMessage);
                    }
                }
                else
                {
                    ShowError(errorTitle, errorMessage);
                }
            }
            else
            {
                errorMessage = $"文件: {Path.GetFileName(filePath)}\n\n未知错误:\n{ex.Message}";
                
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n\n内部异常:\n{ex.InnerException.Message}";
                }

                // 添加通用建议
                errorMessage += "\n\n通用解决建议:\n";
                errorMessage += "• 确保文件路径不包含特殊字符\n";
                errorMessage += "• 尝试将文件复制到简单路径（如C:\\temp\\）\n";
                errorMessage += "• 检查系统资源使用情况\n";
                errorMessage += "• 运行IFC引擎诊断工具";

                var result = MessageBox.Show(
                    errorMessage + "\n\n是否运行引擎诊断？",
                    errorTitle,
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Error);
                
                if (result == MessageBoxResult.Yes)
                {
                    btnTestEngine_Click(this, new RoutedEventArgs());
                }
            }
            
            statusText.Text = "加载失败";
        }

        /// <summary>
        /// 创建简化的测试文件来验证引擎功能
        /// </summary>
        private void CreateSimplifiedTestFile(string originalFilePath)
        {
            try
            {
                var originalDir = Path.GetDirectoryName(originalFilePath) ?? "";
                var simplifiedPath = Path.Combine(originalDir, "simplified_" + Path.GetFileName(originalFilePath));
                
                // 创建一个最简单的IFC文件用于测试
                var simpleIFC = @"ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');
FILE_NAME('simplified_test.ifc','2024-01-01T00:00:00',('Test'),('Test'),'Simplified IFC','Test','Unknown');
FILE_SCHEMA(('IFC4'));
ENDSEC;
DATA;
#1=IFCPROJECT('SimpleTest123456789012','Test Project');
ENDSEC;
END-ISO-10303-21;";
                File.WriteAllText(simplifiedPath, simpleIFC);
                
                var result = MessageBox.Show(
                    $"已创建简化测试文件：\n{simplifiedPath}\n\n是否尝试加载此文件？",
                    "简化测试文件",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);
                
                if (result == MessageBoxResult.Yes)
                {
                    Task.Run(async () =>
                    {
                        await Dispatcher.InvokeAsync(async () =>
                        {
                            await LoadIFCFileAsync(simplifiedPath);
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                ShowError("创建测试文件失败", $"无法创建简化测试文件: {ex.Message}");
            }
        }

        private string GetErrorTypeDescription(IFCLoadError errorType)
        {
            return errorType switch
            {
                IFCLoadError.FileNotFound => "文件未找到",
                IFCLoadError.FileAccessDenied => "文件访问被拒绝",
                IFCLoadError.InvalidFileFormat => "无效的文件格式",
                IFCLoadError.CorruptedFile => "文件已损坏",
                IFCLoadError.UnsupportedSchema => "不支持的IFC架构",
                IFCLoadError.EngineInitializationFailed => "IFC引擎初始化失败",
                IFCLoadError.OutOfMemory => "内存不足",
                IFCLoadError.UnknownError => "未知错误",
                _ => "未定义错误"
            };
        }

        private void SetUIEnabled(bool enabled)
        {
            btnLoadIFC.IsEnabled = enabled;
            btnResetView.IsEnabled = enabled && (_hybridModelManager?.ModelInfo != null);
            btnZoomExtents.IsEnabled = enabled && (_hybridModelManager?.ModelInfo != null);
            btnTestEngine.IsEnabled = enabled;
            btnSystemInfo.IsEnabled = enabled;
        }

        private void ShowLoadingPanel(bool show, string message = "")
        {
            loadingPanel.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
            if (show && !string.IsNullOrEmpty(message))
            {
                loadingText.Text = message;
            }
        }

        private void ShowError(string title, string message)
        {
            MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void ShowInfo(string title, string message)
        {
            MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void UpdateModelInfo()
        {
            try
            {
                if (_hybridModelManager?.ModelInfo == null)
                {
                    txtModelInfo.Text = "未加载模型";
                    return;
                }

                var info = _hybridModelManager.ModelInfo;
                var infoText = $"加载模式: {_hybridModelManager.CurrentMode}\n" +
                              $"文件: {info.FileName}\n" +
                              $"Schema: {info.Schema}\n" +
                              $"实体总数: {info.EntityCount}\n" +
                              $"几何对象: {info.GeometryCount}\n" +
                              $"主要类型:\n";

                var topTypes = info.EntityTypeCount
                    .OrderByDescending(kv => kv.Value)
                    .Take(5);

                foreach (var type in topTypes)
                {
                    infoText += $"  {type.Key}: {type.Value}\n";
                }

                txtModelInfo.Text = infoText;
            }
            catch (Exception ex)
            {
                txtModelInfo.Text = $"更新模型信息时出错: {ex.Message}";
            }
        }

        private void UpdateEntityTree()
        {
            try
            {
                treeEntities.Items.Clear();

                if (_hybridModelManager?.RootEntities == null)
                    return;

                var groupedEntities = _hybridModelManager.RootEntities
                    .GroupBy(e => e.Type)
                    .OrderBy(g => g.Key);

                foreach (var group in groupedEntities)
                {
                    var typeNode = new TreeViewItem
                    {
                        Header = $"{group.Key} ({group.Count()})",
                        Tag = null,
                        FontWeight = FontWeights.Bold
                    };

                    foreach (var entity in group.OrderBy(e => e.Name))
                    {
                        var entityNode = new TreeViewItem
                        {
                            Header = entity.Name,
                            Tag = entity,
                            FontWeight = FontWeights.Normal
                        };

                        // 添加属性子节点
                        if (entity.Properties.Any())
                        {
                            var propsNode = new TreeViewItem
                            {
                                Header = $"属性 ({entity.Properties.Count})",
                                Tag = null,
                                FontStyle = FontStyles.Italic
                            };

                            foreach (var prop in entity.Properties.Where(p => p.IsSet))
                            {
                                var propNode = new TreeViewItem
                                {
                                    Header = $"{prop.Name}: {prop.Value}",
                                    Tag = prop
                                };
                                propsNode.Items.Add(propNode);
                            }

                            entityNode.Items.Add(propsNode);
                        }

                        typeNode.Items.Add(entityNode);
                    }

                    treeEntities.Items.Add(typeNode);
                }
            }
            catch (Exception ex)
            {
                ShowError("更新实体树错误", $"更新实体树时出错: {ex.Message}");
            }
        }

        private void LoadGeometry()
        {
            try
            {
                // 清除现有3D内容
                viewport3D.Children.Clear();

                if (_hybridModelManager?.Geometries == null || !_hybridModelManager.Geometries.Any())
                {
                    statusText.Text = "没有找到几何数据";
                    return;
                }

                var modelGroup = new Model3DGroup();
                int successCount = 0;
                int totalCount = _hybridModelManager.Geometries.Count;

                foreach (var geometry in _hybridModelManager.Geometries)
                {
                    try
                    {
                        var mesh = CreateMeshFromGeometry(geometry);
                        if (mesh != null)
                        {
                            var material = GetMaterialForEntityType(geometry.EntityType);
                            var model = new GeometryModel3D(mesh, material);
                            modelGroup.Children.Add(model);
                            successCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"创建几何体时出错: {ex.Message}");
                    }
                }

                if (modelGroup.Children.Any())
                {
                    var modelVisual = new ModelVisual3D { Content = modelGroup };
                    viewport3D.Children.Add(modelVisual);
                    
                    // 自动缩放到合适大小
                    viewport3D.ZoomExtents();
                }

                var engineMode = _hybridModelManager?.CurrentMode ?? "未知";
                statusText.Text = $"已显示 {successCount}/{totalCount} 个几何对象 ({engineMode})";
            }
            catch (Exception ex)
            {
                ShowError("几何加载错误", $"加载3D几何体时出错: {ex.Message}");
            }
        }

        private MeshGeometry3D? CreateMeshFromGeometry(IFCGeometry geometry)
        {
            if (geometry.Vertices == null || geometry.Indices == null)
                return null;

            try
            {
                var mesh = new MeshGeometry3D();
                
                // 添加顶点 (假设顶点数据是 x,y,z,x,y,z... 格式)
                for (int i = 0; i < geometry.Vertices.Length; i += 3)
                {
                    if (i + 2 < geometry.Vertices.Length)
                    {
                        mesh.Positions.Add(new Point3D(
                            geometry.Vertices[i],
                            geometry.Vertices[i + 1],
                            geometry.Vertices[i + 2]));
                    }
                }

                // 添加索引
                for (int i = 0; i < geometry.Indices.Length; i += 3)
                {
                    if (i + 2 < geometry.Indices.Length)
                    {
                        mesh.TriangleIndices.Add(geometry.Indices[i]);
                        mesh.TriangleIndices.Add(geometry.Indices[i + 1]);
                        mesh.TriangleIndices.Add(geometry.Indices[i + 2]);
                    }
                }

                // 如果没有法线，自动计算
                if (geometry.Normals == null)
                {
                    // 简单的法线计算 - 可以使用更复杂的算法
                    for (int i = 0; i < mesh.Positions.Count; i++)
                    {
                        mesh.Normals.Add(new Vector3D(0, 0, 1)); // 默认向上的法线
                    }
                }
                else
                {
                    for (int i = 0; i < geometry.Normals.Length; i += 3)
                    {
                        if (i + 2 < geometry.Normals.Length)
                        {
                            mesh.Normals.Add(new Vector3D(
                                geometry.Normals[i],
                                geometry.Normals[i + 1],
                                geometry.Normals[i + 2]));
                        }
                    }
                }

                return mesh;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private Material GetMaterialForEntityType(string entityType)
        {
            var color = _entityColors.ContainsKey(entityType) 
                ? _entityColors[entityType] 
                : _entityColors["DEFAULT"];

            return new DiffuseMaterial(color);
        }

        private void UpdateUI()
        {
            try
            {
                var hasModel = _hybridModelManager?.ModelInfo != null;
                
                btnResetView.IsEnabled = hasModel;
                btnZoomExtents.IsEnabled = hasModel;
                
                if (hasModel && _hybridModelManager?.ModelInfo != null)
                {
                    entityCount.Text = _hybridModelManager.ModelInfo.EntityCount.ToString();
                    geometryCount.Text = _hybridModelManager.ModelInfo.GeometryCount.ToString();
                }
                else
                {
                    entityCount.Text = "0";
                    geometryCount.Text = "0";
                    // txtCurrentFile.Text = "未加载文件"; // 注释掉不存在的控件
                    txtModelInfo.Text = "未加载模型";
                    treeEntities.Items.Clear();
                    gridProperties.ItemsSource = null;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新UI时出错: {ex.Message}");
            }
        }

        private void btnResetView_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                viewport3D.ResetCamera();
            }
            catch (Exception ex)
            {
                ShowError("视图操作错误", $"重置视图时出错: {ex.Message}");
            }
        }

        private void btnZoomExtents_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                viewport3D.ZoomExtents();
            }
            catch (Exception ex)
            {
                ShowError("视图操作错误", $"缩放视图时出错: {ex.Message}");
            }
        }

        private void treeEntities_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                if (e.NewValue is TreeViewItem item && item.Tag is IFCEntity entity)
                {
                    DisplayEntityProperties(entity);
                }
                else
                {
                    gridProperties.ItemsSource = null;
                }
            }
            catch (Exception ex)
            {
                ShowError("属性显示错误", $"显示实体属性时出错: {ex.Message}");
            }
        }

        private void DisplayEntityProperties(IFCEntity entity)
        {
            try
            {
                var properties = entity.Properties.Select(p => new
                {
                    Name = p.Name,
                    Value = p.Value,
                    Type = p.Type
                }).ToList();

                gridProperties.ItemsSource = properties;
            }
            catch (Exception ex)
            {
                ShowError("属性显示错误", $"创建属性列表时出错: {ex.Message}");
            }
        }

        private void txtSearch_GotFocus(object sender, RoutedEventArgs e)
        {
            if (!_isSearching && txtSearch.Text == "搜索实体...")
            {
                txtSearch.Text = "";
                txtSearch.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        private void txtSearch_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtSearch.Text))
            {
                _isSearching = false;
                txtSearch.Text = "搜索实体...";
                txtSearch.Foreground = new SolidColorBrush(Colors.Gray);
                UpdateEntityTree(); // 恢复完整树
            }
        }

        private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (_hybridModelManager == null || txtSearch.Text == "搜索实体...")
                    return;

                _isSearching = true;
                
                if (string.IsNullOrWhiteSpace(txtSearch.Text))
                {
                    UpdateEntityTree();
                    return;
                }

                // 执行搜索
                var searchResults = _hybridModelManager.SearchEntities(txtSearch.Text);
                
                treeEntities.Items.Clear();
                
                var groupedResults = searchResults
                    .GroupBy(e => e.Type)
                    .OrderBy(g => g.Key);

                foreach (var group in groupedResults)
                {
                    var typeNode = new TreeViewItem
                    {
                        Header = $"{group.Key} ({group.Count()})",
                        Tag = null,
                        FontWeight = FontWeights.Bold,
                        IsExpanded = true
                    };

                    foreach (var entity in group.OrderBy(e => e.Name))
                    {
                        var entityNode = new TreeViewItem
                        {
                            Header = entity.Name,
                            Tag = entity,
                            FontWeight = FontWeights.Normal
                        };

                        typeNode.Items.Add(entityNode);
                    }

                    treeEntities.Items.Add(typeNode);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"搜索实体时出错: {ex.Message}");
            }
        }

        private void btnTestEngine_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 显示加载进度
                ShowLoadingPanel(true, "正在诊断IFC引擎...");
                statusText.Text = "诊断中...";

                Task.Run(() =>
                {
                    try
                    {
                        var diagnosticResult = IFCDiagnosticTool.RunFullDiagnostic();
                        
                        Dispatcher.Invoke(() =>
                        {
                            ShowLoadingPanel(false);
                            statusText.Text = "诊断完成";
                            
                            if (diagnosticResult.OverallSuccess)
                            {
                                ShowInfo("引擎诊断", "IFC引擎工作正常！\n\n所有组件检查通过，可以正常加载IFC文件。");
                            }
                            else
                            {
                                var detailedReport = IFCDiagnosticTool.GenerateDetailedReport();
                                ShowDiagnosticWindow(detailedReport, diagnosticResult);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        Dispatcher.Invoke(() =>
                        {
                            ShowLoadingPanel(false);
                            statusText.Text = "诊断失败";
                            ShowError("诊断异常", $"运行诊断时出错: {ex.Message}");
                        });
                    }
                });
            }
            catch (Exception ex)
            {
                ShowLoadingPanel(false);
                ShowError("引擎测试错误", $"启动诊断时出错: {ex.Message}");
            }
        }

        private void ShowDiagnosticWindow(string report, DiagnosticResult result)
        {
            var window = new Window
            {
                Title = "IFC引擎诊断报告",
                Width = 600,
                Height = 500,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this
            };

            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            // 报告文本框
            var textBox = new TextBox
            {
                Text = report,
                IsReadOnly = true,
                TextWrapping = TextWrapping.Wrap,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                FontFamily = new FontFamily("Consolas"),
                FontSize = 12,
                Margin = new Thickness(10)
            };
            Grid.SetRow(textBox, 0);
            grid.Children.Add(textBox);

            // 按钮面板
            var buttonPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(10)
            };

            var repairButton = new Button
            {
                Content = "尝试修复",
                Width = 100,
                Height = 30,
                Margin = new Thickness(5),
                IsEnabled = !result.OverallSuccess
            };
            repairButton.Click += (s, e) =>
            {
                try
                {
                    IFCDiagnosticTool.AttemptRepair();
                    MessageBox.Show("修复尝试完成，请重新启动应用程序。", "修复", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"修复失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            };

            var retestButton = new Button
            {
                Content = "重新测试",
                Width = 100,
                Height = 30,
                Margin = new Thickness(5)
            };
            retestButton.Click += (s, e) =>
            {
                window.Close();
                btnTestEngine_Click(s, e);
            };

            var closeButton = new Button
            {
                Content = "关闭",
                Width = 100,
                Height = 30,
                Margin = new Thickness(5)
            };
            closeButton.Click += (s, e) => window.Close();

            buttonPanel.Children.Add(repairButton);
            buttonPanel.Children.Add(retestButton);
            buttonPanel.Children.Add(closeButton);

            Grid.SetRow(buttonPanel, 1);
            grid.Children.Add(buttonPanel);

            window.Content = grid;
            window.ShowDialog();
        }

        private void btnQuickFix_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show(
                    "快速修复将执行以下操作：\n\n" +
                    "• 清理临时文件\n" +
                    "• 重置工作目录\n" +
                    "• 强制垃圾回收\n" +
                    "• 重新初始化IFC引擎\n\n" +
                    "是否继续？",
                    "快速修复确认",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    ShowLoadingPanel(true, "正在执行快速修复...");
                    statusText.Text = "修复中...";

                    Task.Run(() =>
                    {
                        try
                        {
                            // 执行修复
                            IFCDiagnosticTool.AttemptRepair();

                            // 重新初始化模型管理器
                            Dispatcher.Invoke(() =>
                            {
                                try
                                {
                                    _hybridModelManager?.Dispose();
                                    _hybridModelManager = new HybridIFCModelManager();
                                    
                                    UpdateUI();
                                    
                                    ShowLoadingPanel(false);
                                    statusText.Text = "快速修复完成";
                                    
                                    ShowInfo("修复完成", "快速修复已完成，现在可以尝试重新加载IFC文件。");
                                }
                                catch (Exception ex)
                                {
                                    ShowLoadingPanel(false);
                                    statusText.Text = "修复失败";
                                    ShowError("修复失败", $"重新初始化时出错: {ex.Message}");
                                }
                            });
                        }
                        catch (Exception ex)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                ShowLoadingPanel(false);
                                statusText.Text = "修复失败";
                                ShowError("修复失败", $"执行修复时出错: {ex.Message}");
                            });
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                ShowError("快速修复错误", $"启动快速修复时出错: {ex.Message}");
            }
        }

        private void btnSystemInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowLoadingPanel(true, "正在收集系统信息...");
                statusText.Text = "收集信息中...";

                Task.Run(() =>
                {
                    try
                    {
                        var systemInfo = IFCDiagnosticTool.GenerateDetailedReport();
                        
                        Dispatcher.Invoke(() =>
                        {
                            ShowLoadingPanel(false);
                            statusText.Text = "信息收集完成";
                            ShowInfo("系统诊断信息", systemInfo);
                        });
                    }
                    catch (Exception ex)
                    {
                        Dispatcher.Invoke(() =>
                        {
                            ShowLoadingPanel(false);
                            statusText.Text = "信息收集失败";
                            ShowError("系统信息错误", $"获取系统信息时出错: {ex.Message}");
                        });
                    }
                });
            }
            catch (Exception ex)
            {
                ShowLoadingPanel(false);
                ShowError("系统信息错误", $"启动信息收集时出错: {ex.Message}");
            }
        }

        private async void btnLoadTest_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var testFilePath = Path.Combine(
                    Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? "",
                    "test_model.ifc");

                if (!File.Exists(testFilePath))
                {
                    ShowError("测试文件未找到", $"找不到测试IFC文件: {testFilePath}");
                    return;
                }

                LogDebug($"加载测试文件: {testFilePath}");
                await LoadIFCFileAsync(testFilePath);
            }
            catch (Exception ex)
            {
                ShowError("加载测试文件错误", $"加载测试文件时出错: {ex.Message}");
            }
        }

        private void btnAnalyzeDll_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ShowLoadingPanel(true, "正在分析IFC引擎DLL...");
                statusText.Text = "分析中...";

                Task.Run(() =>
                {
                    try
                    {
                        var analysisReport = DllAnalyzer.GenerateAnalysisReport();
                        
                        Dispatcher.Invoke(() =>
                        {
                            ShowLoadingPanel(false);
                            statusText.Text = "DLL分析完成";
                            
                            var window = new Window
                            {
                                Title = "IFC引擎DLL分析报告",
                                Width = 700,
                                Height = 600,
                                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                                Owner = this
                            };

                            var textBox = new TextBox
                            {
                                Text = analysisReport,
                                IsReadOnly = true,
                                TextWrapping = TextWrapping.Wrap,
                                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                                FontFamily = new FontFamily("Consolas"),
                                FontSize = 11,
                                Margin = new Thickness(10)
                            };

                            window.Content = textBox;
                            window.ShowDialog();
                        });
                    }
                    catch (Exception ex)
                    {
                        Dispatcher.Invoke(() =>
                        {
                            ShowLoadingPanel(false);
                            statusText.Text = "DLL分析失败";
                            ShowError("DLL分析错误", $"分析DLL时出错: {ex.Message}");
                        });
                    }
                });
            }
            catch (Exception ex)
            {
                ShowLoadingPanel(false);
                ShowError("DLL分析错误", $"启动DLL分析时出错: {ex.Message}");
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            try
            {
                _hybridModelManager?.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"释放资源时出错: {ex.Message}");
            }
            base.OnClosed(e);
        }

        private void LogDebug(string message)
        {
            System.Diagnostics.Debug.WriteLine($"[MainWindow] {DateTime.Now:HH:mm:ss.fff} DEBUG: {message}");
        }

        private void LogError(string message)
        {
            System.Diagnostics.Debug.WriteLine($"[MainWindow] {DateTime.Now:HH:mm:ss.fff} ERROR: {message}");
        }
    }
}